<html>
  <head>
    <title></title>
    <meta content="">
    <style>
		.green { color: green; }
		.red { color: red; }
		.yellow { color: dark-yellow; }
		
		.entity_types {
			border: 2px solid olive;
			margin-bottom: 20px;
			max-width: 690px;
		}

		.entity_types .header {
			background-color: olive;
			padding: 5px;
		}

		.entity_types .type {
			padding: 2px 5px;
		}
		
 		.entity_types {
			border: 2px solid olive;
			margin-bottom: 20px;
			max-width: 690px;
		}
   
		.entity-table {
			border-collapse: collapse;
		}
		
		.entity-header {
			background-color: pink;
			padding: 5px;
		}
		
		.entity-details {
			border: 2px solid pink;
		}
		
		.entity-details .components {
			padding: 5px;
		}
    
		.newEntity.header {
			background-color: #aaaaff;
			margin-bottom: 0px;
		}
		.newEntity {
			border: 2px solid #aaaaff;
			padding: 5px;
			max-width: 690px;
			margin-bottom: 20px;
		}
		
		.search-tabs {
			margin-bottom: 5px;
			cursor: pointer;
		}
		
		.search-tabs [tab="filter"] {
			background-color: purple;
			color: silver;
			padding: 5px;
		}
		.search-tabs [tab="search"] {
			background-color: #115511;
			color: silver;
			padding: 5px;
		}

		.search-values {
			border: 2px solid #115511;
			max-width: 700px;
			margin-bottom: 20px;
		}


		.search-entities {
			border: 2px solid purple;
			max-width: 700px;
			margin-bottom: 20px;
		}

		
		.search-entities .component-filter {
			padding: 5px;
			float: left;
			clear: both;
		}
		
		.search-entities .component-filter .component-checkbox {
			float: left;
			display: inline-block;
			min-width: 180px;
		}
    
    </style>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    
	<script type="text/javascript" src="./templates.js"></script>
	<script type="text/javascript" src="./ces.js"></script>
	<script type="text/javascript">
		var compData;
		$(function() {
			function refreshEntities() {
				$.getJSON('/entities', function(data, status) {
					$('.entity_list').html(JSON.stringify(data));
				}) 
				
			}
			
			CES.listTypes(function(err, data) {
				$('.entity_types').html(HB['types'](data));
				compData = {componentTypes: data};
			});
			CES.allEntities(function(err, data) {
				$('.entity_list').html(HB['entity'](data)).data('entities', data);
				
			});
			
			
			$(document).on('click', '.newType [action="create"]', function(e) {
				var en = $(e.target);
				var parent = en.closest('.newType');
				var name = parent.find('[name="name"]').val();
				var dataType = parent.find('[name="dataType"]').val();
				
				if(name == '<name>') return;
				
				CES.addType(name, dataType, function(err, data) {
					$('.entity_types').html(HB['types'](data));
				})
				
			});
			
			$(document).on('click', '.entity-header [action="delete"]', function(e) {
				var en = $(e.target);
				var entity = en.closest('.entity-header')
				var eid = entity.attr('eid')|0;
				CES.deleteEntity(eid, function(err, data) {
					console.log('entity deleted ' + eid); 
					$('.entity-header[eid="'+eid+'"]').remove();
					$('.entity-details[eid="'+eid+'"]').remove();
				});
			});
			
			
			$(document).on('click', '.entity-header [action="fetch-components"]', function(e) {
				var en = $(e.target);
				var entity = en.closest('.entity-header')
				var eid = entity.attr('eid')|0;
				console.log('eid: ', eid)
				
				var compdata;
				
				CES.fetchEntity(eid, function(err, comps) {
					console.log('comps: ', comps);
					var ed = $('.entity-details[eid="'+eid+'"]');
					ed.show();
					ed.find('.components').html(HB['components'](comps));
					ed.find('button[action="save"]').show();
					
					CES.listTypes(function(err, data) {
						compdata = {componentTypes: data};
					});
					
					function addComponent() {
						ed.find('.components').append(HB['new_component'](compdata))
					}
					
					
					ed.find('[action="add-component"]').click(function(e) {
						e.preventDefault();
						addComponent();
					});
					
					
					
				});
			});
			
			$(document).on('click', '.entity-details [action="save"]', function(e) {
				console.log('save clicked', e);
				var en = $(e.target);
				var entity_details = en.closest('.entity-details');
				var eid = entity_details.attr('eid')|0;
				
				var new_entity = {eid: eid};
				// existing components
				entity_details.find('input.valedit').each(function() {
					var name = $(this).attr('name');
					var val = $(this).val();
					
					new_entity[name] = val;
				});
				
				// new components. hacky but meh
				entity_details.find('.newcomp').each(function() {
					var name = $(this).find('select[name="type"]').val();
					var val = $(this).find('input[name="value"]').val();
					
					new_entity[name] = val;
				});
				
				console.log(new_entity)
				
				var status_node = entity_details.find('.save_status');
				status_node.html('saving...').removeClass('red green').addClass('yellow');
				
				CES.upsertEntity(new_entity, function(err, data) {
					console.log('upsert Entity callback');
					if(!err) {
						status_node.html('saved!').removeClass('red yellow').addClass('green');
						setTimeout(function() { status_node.html('').removeClass('green'); }, 10000);
					}
					else {
						status_node.html('save failed').removeClass('green yellow').addClass('red');
					}
				});
				
			});
			
			
			function initNewEntity(editor) {
				var ed = $(editor);
				var compdata;
				
				function addComponent() {
					ed.find('.components').append(HB['new_component'](compdata))
				}
				
				CES.listTypes(function(err, data) {
					compdata = {componentTypes: data};
					ed.find('.components').html('');
					addComponent();
				});
				
				ed.find('[action="add-component"]').click(function(e) {
					e.preventDefault();
					addComponent();
				});
				
				ed.find('[action="create-entity"]').click(function(e) {
					var components = {};
					ed.find('.components .newcomp').each(function() {
						var compName = $(this).find('[name="type"]').val();
						var value = $(this).find('[name="value"]').val();
						components[compName] = value;
					});
					
					console.log('new entity', components)
					CES.createEntity(components, function(err, data) {
						console.log('created entity', data);
					});
					
				});
				
			}
			
			initNewEntity('.newEntity');
			
			
			CES.listTypes(function(err, data) {
				$('.search-entities .component-filter').html(HB['search_comp_filter'](data));
			});
			
			$(document).on('click', '.search-entities [action="filter-by-components"]', function(e) {
				var en = $(e.target);
				var se = en.closest('.search-entities');
				var cl = se.find('.component-filter');
				
				var list = [];
				
				cl.find('.component-checkbox input[type="checkbox"]').each(function() {
					if($(this).is(':checked')) {
						list.push($(this).attr('name'));
					}
				});
			
				CES.findEntitiesWithComps(list, function(err, data) {
					$('.entity_list').html(HB['entity'](data)).data('entities', data);
				});
	
				
			});
			
			
			$(document).on('click', '[action="search-values"]', function(e) {
				var t = $(this);
				var sv = t.closest('.search-values');
				
				var components = {};
				sv.find('.components .newcomp').each(function() {
					var compName = $(this).find('[name="type"]').val();
					var value = $(this).find('[name="value"]').val();
					components[compName] = value;
				});
				CES.findEntity(components, function(err, data) {
					$('.entity_list').html(HB['entity'](data)).data('entities', data);
				});
				
			});
			
			$(document).on('click', '[action="Add-component"]', function(e) {
				e.preventDefault();
				var t = $(this);
				$(HB['new_component'](compData)).insertBefore(t);
			});
			
			$('.search-tabs > span[tab]').click(function(e) {
				e.preventDefault();
				
				var t = $(this).attr('tab');
				
				$('.tab').hide();
				$('.tab[tab="'+t+'"]').show();
			});
		});
    </script>
  </head>
  <body>
	<div class="entity_types"></div>	
	
	
	
	<div class="newEntity header">Create Entity</div>
	<div class="newEntity">
		<div class="components"></div>
		<button action="add-component">+</button>
		<br>
		<button action="create-entity">Create Entity</button>

	</div>
	
	
	<div class="search-tabs">
		<span tab="filter">Component Filter</span>
		<span tab="search">Value Search</span>
	</div>
	
	<div class="tab-container">
		<div class="search-entities tab" tab="filter">
			<div class="component-filter">
				
			</div>
			
			<br>
			<button action="filter-by-components" >Apply Filter</button>
		</div>
		
		<div class="search-values tab" tab="search" style="display:none;">
			<div class="components">
				<button action="Add-component">+</button>
			</div>
			
			<br>
			<button action="search-values">Search</button>

		</div>
	</div>

	
	<div class="entity_list"></div>
	
  </body>
</html>
